package com.kinglumi.ailighting.auth.service.biz;

import com.kinglumi.ailighting.auth.base.BaseService;
import com.kinglumi.ailighting.auth.entity.MeshApp;
import com.kinglumi.ailighting.auth.mapper.MeshAppMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lee
 * @date 2021/9/1110:36
 */
@Service
@Slf4j
public class MeshAppService extends BaseService<MeshAppMapper, MeshApp> {

    /**
     * 通过meshId、uuid获取meshApp(address)
     * @param meshId
     * @param uuid
     * @return
     */
    public MeshApp selectByMeshIdAndUuid(Integer meshId, String uuid){
        MeshApp meshApp = new MeshApp();
        meshApp.setMeshId(meshId);
        meshApp.setUuid(uuid);
        meshApp.setActiveStatus(1);
        List<MeshApp> list = super.mapper.select(meshApp);
        return list.size() == 0 ? null: list.get(0);
    }

    /**
     * insert
     * @param meshId
     * @param uuid
     * @return
     */
    public synchronized MeshApp insertMeshApp(Integer meshId, String uuid){
        MeshApp meshApp = new MeshApp();
        meshApp.setMeshId(meshId);
        List<MeshApp> list = super.mapper.select(meshApp);
        MeshApp app = new MeshApp();
        app.setActiveStatus(1);
        app.setUuid(uuid);
        app.setMeshId(meshId);
        app.setAddress(list.size() + 1);
        app.setCreateTime(new Date());
        int id = super.mapper.insert(app);
        app.setId(id);
        return app;
    }

    /**
     * 通过meshId删除所有得meshApp
     * @param meshId
     */
    public void deleteByMeshId(Integer meshId){
        MeshApp meshApp = new MeshApp();
        meshApp.setMeshId(meshId);
        meshApp.setActiveStatus(1);
        List<MeshApp> list = super.mapper.select(meshApp);
        list.forEach(app -> {
            app.setActiveStatus(0);
            super.mapper.updateByPrimaryKeySelective(app);
        });
    }

}
